package cn.edu.nuc.ssm.services.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.nuc.ssm.dao.GcarMapper;
import cn.edu.nuc.ssm.dao.GoodsMapper;
import cn.edu.nuc.ssm.entity.Gcar;
import cn.edu.nuc.ssm.entity.GoodsList;
import cn.edu.nuc.ssm.services.interfaces.GcarService;

@Service
public class GcarServiceImpl implements GcarService {
	
	@Autowired
	private GcarMapper gcarMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	@Override
	public int add(Gcar gcar) {
	    Gcar gcar2 = gcarMapper.selectBy(gcar.getUid(), gcar.getGid());
	    if(gcar2!=null){
    		gcar2.setCgoodsnum(gcar2.getCgoodsnum()+gcar.getCgoodsnum());
	    	
	    	return  gcarMapper.updateByPrimaryKeySelective(gcar2);
	    }	    
		return gcarMapper.insertSelective(gcar);
	}

	@Override
	public List<Gcar> list(Integer uid) {
		
		return gcarMapper.selectListByUid(uid);
	}

	@Override
	public int delt(int uid, int gid) {
		
		return gcarMapper.deleteByUidAndGid(uid, gid);
	}

	@Override
	@Transactional
	public void pay(int uid) {
		List<Gcar> list= list(uid);
			for (Gcar gcar : list) {
				GoodsList gcgood = new GoodsList();
				gcgood.setGoods(goodsMapper.selectByPrimaryKey(gcar.getGid()));
				
				gcgood.setNum(gcar.getCgoodsnum());
				Integer ref = gcgood .getGoods().getGnum()-gcgood.getNum();  
				if(ref < 0 ){
					throw new RuntimeException("库存不足！");
				}
				gcgood.getGoods().setGnum(ref);
				
				goodsMapper.updateByPrimaryKeySelective(gcgood.getGoods());
				
				gcarMapper.deleteByPrimaryKey(gcar.getCid());		
			}
	}

	

}
